package cn.dida.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangzhiling on 16/11/22.
 */
public class QRCodeUtil {

	public static final Log logger = LogFactory.getLog(QRCodeUtil.class);

	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;

	private static final int qrWidth = 200; // 二维码大小
	private static final int qrHeight = 200; // 二维码大小
	private static final String qrFormat = "jpg"; // 二维码的图片格式
	private static final String qrEncode = "UTF-8"; // 二维码编码

	public static void createQrcode(String qrCodeContent, HttpServletResponse response) {

		File qcTemp = null;

		try {
			// 生成二维码矩阵
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			hints.put(EncodeHintType.CHARACTER_SET, qrEncode);
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
			hints.put(EncodeHintType.MARGIN, 0);
			BitMatrix bitMatrix = new QRCodeWriter().encode(qrCodeContent, BarcodeFormat.QR_CODE, qrWidth, qrHeight,
					hints);

			// 生成二维码写入文件
			// qcTemp = new File(qrTempUrl);
			// QRCodeUtil.writeToFile(bitMatrix, qrFormat, qcTemp);
			BufferedImage image = toBufferedImage(bitMatrix);
			ImageIO.write(image, "JPEG", response.getOutputStream());

		} catch (Exception ex) {
			ExceptionUtil.logerErrorMes(logger, ex);
		}
	}

	public static BufferedImage toBufferedImage(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}

	public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		if (!ImageIO.write(image, format, file)) {
			throw new IOException("Could not write an image of format " + format + " to " + file);
		}
	}

	public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		if (!ImageIO.write(image, format, stream)) {
			throw new IOException("Could not write an image of format " + format);
		}
	}

}
